package com.erp.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.erp.dao.UserDAO;

import com.erp.dao.ResourcesDAO;
import com.erp.entity.Resources;
import com.erp.entity.Users;
import com.erp.form.ErpObject;

//2 用户拥有的权限 	
@SuppressWarnings({"deprecation","rawtypes"})
public class MyUserDetailServiceImp implements UserDetailsService {
	
	private UserDAO userMapper;
	private final String username = "";
	private ResourcesDAO resourcesMapper;
	private int id;


	public UserDAO getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserDAO userMapper) {
		this.userMapper = userMapper;
	}

	public ResourcesDAO getResourcesMapper() {
		return resourcesMapper;
	}

	public void setResourcesMapper(ResourcesDAO resourcesMapper) {
		this.resourcesMapper = resourcesMapper;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	// 登录验证

	public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException {

		// 这里应该可以不用再查了
		List list = this.userMapper.findByName(username);

		Users user = null;

		if (list.size() != 0) {
			user = (Users) list.get(0);
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
		UsersDetail userdetail = new UsersDetail(user.getPassWord(),user.getUserName(),user.getUserName(),grantedAuths, user.getId());
		userdetail.setCurrent(user.getCurrent());//设置当前角色
		return userdetail;
	}

	// 取得用户的权限

	private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {

		List<ErpObject> resources = null;
		resources = resourcesMapper.findbyuserid(user.getId());
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		if (resources == null) {
			return authSet;
		}
		for (ErpObject res : resources) {
			authSet.add(new GrantedAuthorityImpl(((Resources)res).getName()));
			// System.out.print(res.getName());
		}
		return authSet;
	}

}
